package com.gouying.mall.rabbit.mq;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Hashtable;
import java.util.Map;

/**
 * toptic 在绑定的时候添加路由键 *，# 可以模糊匹配
 * 绑定时候topic.route.*
 * 生产topic.route.one能发送成功topic.route.one.two这样就不行了
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class HeaderRabbitMq {

    private static final String exchange_name = "exchange.header8";

    private static final String queue_name = "queue.header8";

    private static final String routingKey = "header#";


    @Autowired
    RabbitAdmin rabbitAdmin;

    @Autowired
    RabbitTemplate rabbitTemplate;


    @Test
    public void binding() {
        // 交换机 header
        HeadersExchange exchange = new HeadersExchange(exchange_name, true, false, null);
        rabbitAdmin.declareExchange(exchange);

        //队列
        Queue queue = new Queue(queue_name, true, false, false, null);
        rabbitAdmin.declareQueue(queue);

        //就是又age就行
//        BindingBuilder.bind(queue).to(exchange).where("age").exists();
        //
        // 目的地就是交换机发送到哪的地方 这里发送到队列  这个是all
        Binding bin = BindingBuilder.bind(queue).to(exchange).whereAny("age","name","gen").exist();
        //any
//        BindingBuilder.bind(queue).to(exchange).whereAny("age");
        rabbitAdmin.declareBinding(bin);
    }


    @Test
    public void send() {
        Map<String, Object> headers = new Hashtable<String, Object>();
        headers.put("11232", "jack");
        headers.put("434555", 30);
        String content = headers.toString();
        MessageProperties props = MessagePropertiesBuilder.newInstance()
                .setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN).
                setMessageId("123")
                .setHeader("age", "30")
                .setHeader("name", "zhangsan")
                .setHeader("gen", "gen")
                .build();
        Message message = MessageBuilder.withBody(content.getBytes()).andProperties(props).build();
        rabbitTemplate.convertAndSend(exchange_name,"", message);
    }

    @Test
    public void getMsg() {
//        Message receive = rabbitTemplate.receive("test-queue");
//        System.out.println(JSON.toJSONString(receive));
    }

}
